package com.example.news;

import android.content.Intent;
import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.RecyclerView;

import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

import com.example.news.adapter.NewsInfo;
import com.example.news.adapter.NewsListAdapter;
import com.google.gson.Gson;

import java.io.IOException;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;


public class TabNewsFragment extends Fragment {

    private String url="http://v.juhe.cn/toutiao/index?key=c1972321f267916c11b89728c52d75f2&type=";
    private View rootView;
    private RecyclerView recyclerView;
    private NewsListAdapter mNewsListAdapter;
    private static final String ARG_PARAM = "title";//传入页面的参数
    private String title;


    public TabNewsFragment() {

    }

    public static TabNewsFragment newInstance(String param) {
        TabNewsFragment fragment = new TabNewsFragment();
        Bundle args = new Bundle();//Bundle主要用于传递数据；它保存的数据，是以key-value(键值对)的形式存在的。
        args.putString(ARG_PARAM, param);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            title = getArguments().getString(ARG_PARAM);
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        //创建和获取Fragment视图
        rootView=inflater.inflate(R.layout.fragment_tab_news, container, false);
        //初始化控件,view用户界面的一部分，也可作为控件
        recyclerView=rootView.findViewById(R.id.recycleView);
        return rootView;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        //初始化适配器
        //getActivity():返回一个和此fragment绑定的FragmentActivity或者其子类的实例
        mNewsListAdapter=new NewsListAdapter(getActivity());
        //设置adapter
        recyclerView.setAdapter(mNewsListAdapter);

        //recyclerView列表点击事件
        mNewsListAdapter.setOnItemClickListener(new NewsListAdapter.onItemClickListener() {
            @Override
            public void onItemClick(NewsInfo.ResultDTO.DataDTO dataDTO, int position) {
                //ResultDTO操作结果的数据传输对象,DataDTO数据传输对象
                //跳转到详情页
                Intent intent=new Intent(getActivity(),NewsDetailsActivity.class);
                //传递对象的时候，该类一定要实现Serializable
                intent.putExtra("dataDTO", dataDTO);
                startActivity(intent);
            }
        });
        //获取数据
        getHttpData();
    }

    //从网络（HTTP 协议）获取数据
    private void getHttpData() {
        //创建OkHttpClient对象
        OkHttpClient okHttpClient=new OkHttpClient();
        //构造Request对象
        Request request = new Request.Builder()
                .url(url+title)
                .get()
                .build();
        //通过OkHttpClient和Request对象来构建Call对象
        Call call = okHttpClient.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(@NonNull Call call, @NonNull IOException e) {

            }

            @Override
            public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
                String data = response.body().string();
                //不能在耗时操作里面更新UI，要使用Handler
                Message message=new Message();
                message.what=100;//标识
                message.obj=data;
                //发送
                mHandler.sendMessage(message);
            }
        });
    }
    //Looper.myLooper():获取当前线程的消息循环
    private Handler mHandler=new Handler(Looper.myLooper()){
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            if(msg.what==100){
                String data=(String) msg.obj;
                //导入数据到NewsInfo，Gson库是用于在Java对象和JSON数据之间进行序列化和反序列化的库
                NewsInfo newsInfo = new Gson().fromJson(data, NewsInfo.class);
                if(newsInfo!=null && newsInfo.getError_code()==0){
                    //逻辑处理
                    if(null!=mNewsListAdapter){
                        mNewsListAdapter.setListData(newsInfo.getResult().getData());
                    }
                }else{
                    Toast.makeText(getActivity(),"获取数据失败,请稍后重试",Toast.LENGTH_SHORT).show();
                }
            }
        }
    };

}